/*
 *    Copyright (c) 2018-2025, 云集汇通 All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yunjihuitong.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 */

package com.yjht.modules.sys.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yjht.common.constant.Constant;
import com.yjht.common.func.datafilter.DataFilter;
import com.yjht.common.utils.PageUtils;
import com.yjht.common.utils.ParamsUtils;
import com.yjht.common.utils.Query;
import com.yjht.modules.sys.dao.SysUserDao;
import com.yjht.modules.sys.entity.SysDeptEntity;
import com.yjht.modules.sys.entity.SysUserEntity;
import com.yjht.modules.sys.service.SysDeptService;
import com.yjht.modules.sys.service.SysUserRoleService;
import com.yjht.modules.sys.service.SysUserService;
import com.yjht.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 *
 * @author lengleng
 * @email wangiegie@gmail.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysDeptService sysDeptService;

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    @DataFilter(subDept = true, user = false)
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("username");

        Page<SysUserEntity> page = this.selectPage(
                new Query<SysUserEntity>(params).getPage(),
                new EntityWrapper<SysUserEntity>()
                        .like(StringUtils.isNotBlank(username), "username", username)
                        .addFilterIfNeed(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
        );

        for (SysUserEntity sysUserEntity : page.getRecords()) {
            SysDeptEntity sysDeptEntity = sysDeptService.selectById(sysUserEntity.getDeptId());
            sysUserEntity.setDeptName(sysDeptEntity.getName());
        }

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserEntity user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
        this.insert(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
        }
        this.updateById(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }


    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new EntityWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }

    @Override
    @DataFilter(subDept = true, user = false)
    public PageUtils querySysUserList(Map<String, Object> params, Query<SysUserEntity> query) {
        String keyword;
        String role_id;
        role_id = "2";
        keyword = "wjk";
        Page page = query.getPage();
        page.setCondition(params);
        EntityWrapper<SysUserEntity> ew = new EntityWrapper<SysUserEntity>();
        SysUserEntity condition = new SysUserEntity();
        ew.setEntity(condition);
        ew.like("username", keyword);
        ew.or().like("u.user_id", keyword);
        ew.or().like("dept_name", keyword);
        ew.andNew().eq("ur.role_id", role_id);
        params = ParamsUtils.getNewSqlFilter(params,"u");
        ew.addFilterIfNeed(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER));
        List<SysUserEntity> list = baseMapper.querySysUserListPage1(page, ew);
        page.setRecords(list);
        return new PageUtils(page);
    }

    /**
     * 查下用户全部权限
     *
     * @param userId userId
     * @return
     */
    @Override
    @Cacheable(value = "sys:perms", key = "#userId")
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }
}
